<script setup>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { onMounted } from "vue";
import { searchDataJbfa } from "@/api/search";
import { addOrUpdateJbfa } from "@/api/addOrUpdate";

const editorRef = shallowRef();
const valueHtml = ref(
  "<p>主要明确人防专业力量编成、力量部署、任务区分等内容。</p>"
);
const toolbarConfig = {};
const editorConfig = { placeholder: "请输入内容..." };
const mode = ref("default");

// 加载html
const initHtml = () => {
  searchDataJbfa ({ m: "力量运用-引言" }).then((res) => {
    if (res.code !== 200)  return ElMessage.error(res.msg)
    const { data } = res;
    valueHtml.value = data.find((x) => x.k === "力量运用引言")?.v || "";
  });
};

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

// 保存
const saveProgramme = () => {
  ElMessageBox.confirm(`确定要保存吗?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    customClass: "message-box",
  }).then(() => {
    addOrUpdateJbfa ({
      m: "力量运用-引言",
      data: [
        {
          k: "力量运用引言",
          v: valueHtml.value,
        },
      ],
    })
      .then(() => {
        ElMessage.success("操作成功");
      })
      .catch(() => {});
  });
};

onMounted(() => {
  initHtml();
});

onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>
<template>
  <div class="box">
    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 500px; overflow-y: hidden"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>
    <el-button type="primary" class="save-btn" @click="saveProgramme"
      >保存</el-button
    >
  </div>
</template>
<style scoped lang="scss"></style>
